package com.lgc.eventsounds;

import java.io.InputStream;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;

public class SoundPlayer {
  private static final int EXTERNAL_BUFFER_SIZE = 128000;

  public static void playSoundFile(String fileName,boolean doPlay)
  {
    if(!doPlay)
      return;
    AudioInputStream audioInputStream = null;
    try {
      InputStream soundFile = FileResourceLoader.getFileResource(fileName);
      audioInputStream = AudioSystem.getAudioInputStream(soundFile);
    } catch(Throwable t) {
      return;
    }
    AudioFormat audioFormat = audioInputStream.getFormat();
    SourceDataLine line = null;
    DataLine.Info info = new DataLine.Info(SourceDataLine.class,audioFormat);
    try {
      line = (SourceDataLine)AudioSystem.getLine(info);
      line.open(audioFormat);
    } catch(Throwable t) {
      return;
    }
    line.start();
    int nBytesRead = 0;
    byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
    while(nBytesRead != -1) {
      try {
        nBytesRead = audioInputStream.read(abData, 0, abData.length);
      } catch(Throwable t) {
        return;
      }
      if(nBytesRead >= 0)
        line.write(abData, 0, nBytesRead);
    }
    line.drain();
    line.close();
  }
}
